<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列表渲染-列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!-- 
        v-for指令
            1.用于展示列表数据
            2.语法：v-for="（item.index） in xxx" :key="index"
            3.可遍历：数组/对象/字符串（用的少）/指定次数（用的很少）
     -->

    <div id="root">
        <h2>列表排序</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <button @click="sortType = 2">年龄升序</button>
        <button @click="sortType = 1">年龄降序</button>
        <button @click="sortType = 0">原顺序</button>
        <ul>
            <li v-for="(person,index) in filterPersonList" :key="person.id">
                {{person.name}}-{{person.age}}-{{person.sex}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">

    //用computed实现
    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            sortType: 0, //0-原顺序 1-降序 2-升序
            personList: [
                { id: 1, name: '马冬梅', age: 18, sex: '女' },
                { id: 2, name: '周冬雨', age: 17, sex: '女' },
                { id: 3, name: '周杰伦', age: 21, sex: '男' },
                { id: 4, name: '温兆伦', age: 25, sex: '男' }
            ],
        },
        computed: {
            filterPersonList() {
                const arr = this.personList.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                })
                if (this.sortType) {
                    arr.sort((v1, v2) => {
                        return this.sortType === 1 ? v2.age - v1.age : v1.age - v2.age
                    })
                }
                return arr

            }
        }
    })
</script>

</html>